package com.ruoyi.controller;

import java.util.*;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.mapper.SysDeptMapper;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.domain.RecoverStation;
import com.ruoyi.service.IRecoverStationService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;


/**
 * 回收站Controller
 * 
 * @author ya
 * @date 2025-08-01
 */
@RestController
@RequestMapping("/station/station")
public class RecoverStationController extends BaseController
{
    @Autowired
    private IRecoverStationService recoverStationService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysDeptMapper sysDeptMapper;


    /**
     * 恢复数据到文章表
     */
    @PostMapping("/recoverData/{recoverIds}")
    public AjaxResult recoverData(@PathVariable Long[] recoverIds){
        if (recoverIds == null || recoverIds.length == 0) {
            return error("请选择要恢复的数据");
        }
        // 返回操作结果和恢复数量
        AjaxResult ajaxResult = AjaxResult.success();
        int count = recoverStationService.recoverData(recoverIds);
        ajaxResult.put("msg", "成功恢复 " + count + " 条数据");

        return ajaxResult;
    }


    /**
     * 判断部门是否直接隶属于荆州市长江河道管理局（一级子部门）
     * @param dept 部门信息
     * @param sysDeptMapper 部门Mapper
     * @return 是否直接隶属于荆州市长江河道管理局
     */
    private static boolean isDirectSubDeptOfJingZhou(SysDept dept, SysDeptMapper sysDeptMapper) {
        // 如果部门本身就是"荆州市长江河道管理局"，则不认为是其下级部门
        if ("荆州市长江河道管理局".equals(dept.getDeptName())) {
            return false;
        }
        
        // 直接检查父部门是否为"荆州市长江河道管理局"
        // 如果父部门ID有效，直接查询父部门名称
        if (dept.getParentId() != null && dept.getParentId() > 0) {
            SysDept parentDept = sysDeptMapper.selectDeptById(dept.getParentId());
            if (parentDept != null && "荆州市长江河道管理局".equals(parentDept.getDeptName())) {
                return true;
            }
        }
        
        return false;
    }

    /**
     * 根据用户所属部门判断是否具有管理权限
     * @param sysUser 用户信息
     * @param sysDeptMapper 部门Mapper
     * @return 是否具有管理权限
     */
    private static boolean hasManagerPermission(SysUser sysUser, SysDeptMapper sysDeptMapper) {
        String userName = sysUser.getUserName();

        // 判断是否为管理员账户
        boolean isSuperAdmin = "admin".equals(userName);
        boolean hasManagerPermission = isSuperAdmin;

        // 如果不是超级管理员，则检查部门权限
        if (!isSuperAdmin && sysUser.getDept() != null) {
            // 获取用户所属部门
            SysDept userDept = sysUser.getDept();
            String deptName = userDept.getDeptName();

            // 根据部门名称判断权限：
            if (deptName != null) {
                if ("市局/总局".equals(deptName)) {
                    // 市局/总局具有管理权限
                    hasManagerPermission = true;
                } else if (isDirectSubDeptOfJingZhou(userDept, sysDeptMapper)) {
                    // 直接隶属于荆州市长江河道管理局的部门不具有全局管理权限
                    hasManagerPermission = false;
                } else {
                    // 其他部门，通过 ancestors 字段判断是否属于市局/总局或直接隶属于荆州市长江河道管理局的部门
                    String ancestors = userDept.getAncestors();
                    if (ancestors != null && !ancestors.isEmpty()) {
                        // 从 ancestors 中提取所有祖先部门ID
                        String[] ancestorIds = ancestors.split(",");

                        // 查询祖先部门中名称为"市局/总局"或直接隶属于荆州市长江河道管理局的部门
                        boolean foundManagerDept = false;
                        for (String ancestorId : ancestorIds) {
                            if (!ancestorId.trim().isEmpty()) {
                                try {
                                    Long deptId = Long.parseLong(ancestorId.trim());
                                    SysDept ancestorDept = sysDeptMapper.selectDeptById(deptId);
                                    if (ancestorDept != null &&
                                            ("市局/总局".equals(ancestorDept.getDeptName()))) {
                                        foundManagerDept = true;
                                        break;
                                    }
                                    if (ancestorDept != null &&
                                            (isDirectSubDeptOfJingZhou(ancestorDept, sysDeptMapper))) {
                                        foundManagerDept = false;
                                        break;
                                    }
                                } catch (NumberFormatException e) {
                                    // 忽略无效ID
                                }
                            }
                        }
                        hasManagerPermission = foundManagerDept;
                    } else {
                        hasManagerPermission = false;
                    }
                }
            }
        }

        return hasManagerPermission;
    }

    /**
     * 获取用户部门对应的文章来源（直接隶属于荆州市长江河道管理局的部门名称）
     * 通过祖先部门查找所属的直接隶属于荆州市长江河道管理局的部门
     */
    private String getDeptArticleOrigin(SysUser sysUser) {
        if (sysUser.getDept() == null) {
            return null;
        }

        // 如果当前部门直接隶属于荆州市长江河道管理局，直接返回
        SysDept currentDept = sysUser.getDept();
        if (isDirectSubDeptOfJingZhou(currentDept, sysDeptMapper)) {
            return currentDept.getDeptName();
        }

        // 否则通过祖先部门查找
        String ancestors = currentDept.getAncestors();
        if (ancestors != null && !ancestors.isEmpty()) {
            // 从 ancestors 中提取所有祖先部门ID
            String[] ancestorIds = ancestors.split(",");

            // 查询祖先部门中直接隶属于荆州市长江河道管理局的部门
            for (String ancestorId : ancestorIds) {
                if (!ancestorId.trim().isEmpty()) {
                    try {
                        Long deptId = Long.parseLong(ancestorId.trim());
                        SysDept ancestorDept = sysDeptMapper.selectDeptById(deptId);
                        if (ancestorDept != null && ancestorDept.getDeptName() != null &&
                                isDirectSubDeptOfJingZhou(ancestorDept, sysDeptMapper)) {
                            return ancestorDept.getDeptName();
                        }
                    } catch (NumberFormatException e) {
                        // 忽略无效ID
                    }
                }
            }
        }

        return null;
    }



    /**
     * 查询回收站列表：权限控制
     */
    @PreAuthorize("@ss.hasPermi('station:station:list')")
    @GetMapping("/list")
    public Map<String, Object> list(RecoverStation recoverStation) {
        startPage();
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser sysUser = loginUser.getUser();
        String userName = sysUser.getUserName();

        // 使用基于部门的权限判断
        boolean hasManagerPermission = hasManagerPermission(sysUser, sysDeptMapper);

        // 如果是分局用户，添加部门权限过滤条件
        if (!hasManagerPermission && sysUser.getDept() != null) {
            String articleOrigin = getDeptArticleOrigin(sysUser);
            if (articleOrigin != null) {
                // 强制设置type为1（uncheck表回收的数据）
                recoverStation.setType(1L);
                // 设置文章来源为当前分局
                recoverStation.setArticleOrigin(articleOrigin);
            }
        }

        List<RecoverStation> list = recoverStationService.selectRecoverStationList(recoverStation, userName, hasManagerPermission);
        TableDataInfo tableDataInfo = getDataTable(list);
        HashMap<String, Object> result = new HashMap<>();
        result.put("data", tableDataInfo);
        result.put("allowedAll", hasManagerPermission);

        return result;
    }


    /**
     * 导出回收站列表
     */
//    @PreAuthorize("@ss.hasPermi('station:station:export')")
//    @Log(title = "回收站", businessType = BusinessType.EXPORT)
//    @PostMapping("/export")
//    public void export(HttpServletResponse response, RecoverStation recoverStation)
//    {
//        List<RecoverStation> list = recoverStationService.selectRecoverStationList(recoverStation,allowAll);
//        ExcelUtil<RecoverStation> util = new ExcelUtil<RecoverStation>(RecoverStation.class);
//        util.exportExcel(response, list, "回收站数据");
//    }

    /**
     * 获取回收站详细信息
     */
    @PreAuthorize("@ss.hasPermi('station:station:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(recoverStationService.selectRecoverStationById(id));
    }

    /**
     * 新增回收站
     */
    @PreAuthorize("@ss.hasPermi('station:station:add')")
    @Log(title = "回收站", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody RecoverStation recoverStation)
    {
        return toAjax(recoverStationService.insertRecoverStation(recoverStation));
    }

    /**
     * 修改回收站
     */
    @PreAuthorize("@ss.hasPermi('station:station:edit')")
    @Log(title = "回收站", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody RecoverStation recoverStation)
    {
        return toAjax(recoverStationService.updateRecoverStation(recoverStation));
    }

    /**
     * 删除回收站
     */
    @PreAuthorize("@ss.hasPermi('station:station:remove')")
    @Log(title = "回收站", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(recoverStationService.deleteRecoverStationByIds(ids));
    }
}
